using UnityEngine;
using QFramework;
using QFramework.Example;
using System.Collections.Generic;

namespace ProjectSurvivor
{
	public partial class RotateSword : ViewController//武器
	{
		private List<Collider2D> mSwords = new List<Collider2D>();
		public BindableProperty<bool> SuperRotateSword = new(true);
		void Start()
		{
			// Code Here
			//敌人都添加了hurt脚本,当碰到时,会调用Hurt方法,参数为2
			Sword.Hide();
			void CreateSword()
			{
				mSwords.Add(Sword.InstantiateWithParent(this).Show().Self(self =>
{
	self.OnTriggerEnter2DEvent(collider =>
	{
		var hurtBox = collider.GetComponent<HurtBox>();
		if (hurtBox)
		{
			if (hurtBox.Owner.CompareTag("Enemy"))
			{
				var damageTimes = SuperRotateSword.Value ? Random.Range(2, 3 + 1) : 1;
				DamageSystem.CalculateDamage(Global.RotateSwordDamage.Value * damageTimes,
				hurtBox.Owner.GetComponent<Enemy>());
				if (Random.Range(0, 1.0f) < 0.5f)
				{
					collider.attachedRigidbody.velocity = collider.NormalizedDirection2DFrom(self) * 5
					+ collider.NormalizedDirection2DFrom(Player.Default) * 10;
				}
			}
		}
	}).UnRegisterWhenGameObjectDestroyed(self);
}).Show());
			}
			void CreateSwords()
			{
				var toAddCount = Global.RotateSwordCount.Value + Global.AdditionalFlyThingCount.Value - mSwords.Count;
				for (var i = 0; i < toAddCount; i++)
				{
					CreateSword();
				}
				UpdateCirclePos();
			}
			Global.RotateSwordCount.Or(Global.AdditionalFlyThingCount)
			.Register(CreateSwords)
			.UnRegisterWhenGameObjectDestroyed(gameObject);

			Global.RotateSwordRange.Register((range) =>
			{
				UpdateCirclePos();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			CreateSwords();

		}

		void UpdateCirclePos()
		{
			//// 获取旋转半径
			var radius = Global.RotateSwordRange.Value;
			// 每把剑之间的角度
			var durationDegrees = 360 / mSwords.Count;
			// 遍历子弹,设置其位置和角度
			for (var i = 0; i < mSwords.Count; i++)
			{
				// 计算子弹的位置            Deg2Rad角度转弧度
				var circleLocalPos = new Vector2(Mathf.Cos(durationDegrees * i * Mathf.Deg2Rad),
				 Mathf.Sin(durationDegrees * i * Mathf.Deg2Rad)) * radius;
				 // 设置子弹的位置和角度
				mSwords[i].LocalPosition(circleLocalPos.x, circleLocalPos.y)
	   .LocalEulerAnglesZ(durationDegrees * i - 90);
			}

		}
		private void Update()
		{
			//设置速度
			var speed = SuperRotateSword.Value ? Time.frameCount * 10 : Global.RotateSwordSpeed.Value * Time.frameCount;
			// 旋转
			this.LocalEulerAnglesZ(-speed);
		}
	}
}
